package com.geyue.common.util;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.nutz.lang.random.R;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

/**
 * Created by Lyon on 2017/4/10.
 */
public class ImageUtil {

    /**
     * 获取图片高度
     * @param imagePath
     * @return 图片高度
     * @throws Exception
     */
    public static int height(String imagePath) throws Exception{
        BufferedImage image = ImageIO.read(new File(imagePath));
        return image.getHeight();
    }

    /**
     * 获取图片宽度
     * @param imagePath
     * @return 图片宽度
     * @throws Exception
     */
    public static int width(String imagePath) throws Exception{
        BufferedImage image = ImageIO.read(new File(imagePath));
        return image.getWidth();
    }

    /**
     * 图片缩放
     * @param imagePath
     * @return 文件名称
     * @throws Exception
     */
    public static String zoom(String imagePath) throws Exception{
        BufferedImage image = ImageIO.read(new File(imagePath));
        int width = image.getWidth();
        int height = image.getHeight();
        //图片文件
        File file = new File(imagePath);

        if(width > 1280 || height > 1280){
            if(width > height)
                image = Thumbnails.of(imagePath).width(1280).asBufferedImage();
            else
                image = Thumbnails.of(imagePath).height(1280).asBufferedImage();

            Thumbnails.Builder<BufferedImage> builder = Thumbnails.of(image).sourceRegion(Positions.CENTER, 1280, 1280).size(1280, 1280);
            String imgFile = R.UU32();
            builder.outputFormat("jpg").toFile(file.getParent() + imgFile);
            return imgFile + ".jpg";
        }else
            return file.getName();
    }

    /**
     * 图片格式转换为JPG
     * @param imagePath
     * @return 文件名称
     * @throws Exception
     */
    public static String format(String imagePath) throws Exception{
        Thumbnails.Builder<File> builder = Thumbnails.of(imagePath).scale(1f);
        String path = new File(imagePath).getParent();
        String imgFile = R.UU32();
        builder.outputFormat("jpg").toFile(path + imgFile);
        return imgFile + ".jpg";
    }

}
